<?php

namespace app\modules\sample\controllers;

use Yii;
use app\modules\sample\models;
use yii\data\ActiveDataProvider;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use app\components\PtAccessControl;

/**
 * PositionController implements the CRUD actions for SampleFrom model.
 */
class FromController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
            'pt_access' => [
                'class' => PtAccessControl::className(),
            ]
        ];
    }

    /**
     * Lists all SampleFrom models.
     * @return mixed
     */
    public function actionIndex()
    {
        $dataProvider = new ActiveDataProvider([
            'query' => models\SampleFrom::find(),
        ]);

        return $this->render('index', [
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single SampleFrom model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        $model = $this->findModel($id);

        return $this->render('//sample/from', [
            'view' => 'view',
            'model' => $model,
        ]);
    }

    /**
     * Creates a new SampleFrom model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreateFrom()
    {
        $pt_id = Yii::$app->session->get('pt_id');

        $model = new models\SampleFrom();
        $model->pt_id = $pt_id;
        
        $post = Yii::$app->request->post();

        $msg = $this->testData($post);
        if ($msg != '') {
            return $msg;
        }

        return $this->save($post, $model, $pt_id);
    }

    /**
     * Updates an existing SampleFrom model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $pt_id = Yii::$app->session->get('pt_id');
        $model = $this->findModel($id);
        $post = Yii::$app->request->post();

        if (count($post)) {
            $deliver = ($model->deliver_id == 0) ? new models\SampleDeliver() : $model->deliver[0];
            $deliver->load($post);
            $model->deliver_id = ($deliver->tube_deliver != '') ? $this->saveDeliver($deliver) : 0;

            $model->crt_name = Yii::$app->user->identity->username;
            $model->crt_time = date("Y-m-d H:i:s");
            if ($model->load($post) && $model->save()) {
                return 'success';
            }
            
            return var_dump($model->errors);
        } else {
            return $this->render('//sample/from', [
                'view' => 'update',
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing SampleFrom model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the SampleFrom model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return SampleFrom the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = models\SampleFrom::find()->where(['pk_id' => $id])->with('deliver')->one()) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    protected function save($post, $model, $pt_id)
    {
        $deliver = new models\SampleDeliver();
        $deliver->load($post);
        $model->deliver_id = ($deliver->tube_deliver != '') ? $this->saveDeliver($deliver) : 0;

        $model->crt_name = Yii::$app->user->identity->username;
        $model->crt_time = date("Y-m-d H:i:s");
        if ($model->load($post) && $model->save()) {

            if (($msg = $this->saveDnaid($post)) !== '') {
                return $msg;
            }

            if (($msg = $this->savePosition($post, $model->pk_id)) !== '') {
                return $msg;
            }

            // return $this->saveXna($model, $pt_id);
            return 'success';
            
        } else {
            return var_dump($model->errors);
        }
    }

    protected function saveDnaid($post)//save patient's dna_id; patient->dna_id
    {
        if (isset($post['dna_id']) && $post['dna_id'] != '') {
            $patient = models\Patient::findOne(['pk_id' => Yii::$app->session->get('pt_id')]);
            $patient->dna_id = $post['dna_id'];
            if ($patient->save()) {
                Yii::$app->session->set('dna', $patient->dna_id);
                return '';
            }
            return 'save error';
        }
        return 'dna_id error';
    }

    protected function savePosition($post, $from_id)
    {
        if (count($post) <= 1) return 'error';
        
        for ($i = 0; $i < count($post['xna_id']); $i ++) {
            $model = new models\SamplePosition();
            $model->pt_id = Yii::$app->session->get('pt_id');
            $model->from_id = $from_id;
            $model->xna_id = $post['xna_id'][$i];
            $model->xna_type = ($post['xna_type'][$i] == 'dna') ? 1 : 2;
            $model->case = $post['case'][$i];
            $model->case_a = $post['case_a'][$i];
            $model->case_b = $post['case_b'][$i];
            $model->xna_x = $post['xna_x'][$i];
            $model->xna_y = $post['xna_y'][$i];
            $model->xna_z = $post['xna_z'][$i];
            $model->crt_name = Yii::$app->user->identity->username;
            $model->crt_time = date("Y-m-d H:i:s");
            if (!$model->save()) {
                var_dump($model->errors);
                return 'update position error';
            }
        }

        return '';
    }

    protected function testData($data) {

        if ($data['SampleFrom']['rna_total'] > 2) {
            return 'RNA提取管数不能超过2, ';
        }

        return '';
    }

    protected function saveDeliver($deliver)
    {
        $deliver->pt_id = Yii::$app->session->get('pt_id');
        $deliver->from_type = 1;
        $deliver->crt_name = Yii::$app->user->identity->username;
        $deliver->crt_time = date("Y-m-d H:i:s");
        if (!$deliver->save()) {
            var_dump($deliver->errors);
            return 'save deliver error';
        }
        return $deliver->pk_id;
    }

    protected function saveXna($model, $pt_id)
    {
        $total = array();

        $dna = $this->findInfo($pt_id, 1);
        $total['dna'] = $dna->dna_total;

        $dna->alcohol_80 = intval($dna->alcohol_80) + $model->dna_total;
        $dna->dna_total = intval($dna->dna_total) + $model->dna_total;

        if (!$dna->save()) {
            return 'DNA信息保存失败, ';
        }

        $rna = $this->findInfo($pt_id, 2);
        $total['rna'] = $rna->rna_total;

        $rna->rna_total = intval($rna->rna_total) + $model->rna_total;
        if ($model->rna_total == 1) {
            if ($rna->rna_a == 1 && $rna->rna_b == 0) {
                $rna->rna_b = intval($rna->rna_b) + 1;
            } else {
                $rna->rna_a = intval($rna->rna_a) + 1;
            }
        } else if ($model->rna_total == 2) {
            $rna->rna_b = intval($rna->rna_b) + 1;
            $rna->rna_a = intval($rna->rna_a) + 1;
        } else if ($model->rna_total > 2) {
            return 'RNA管数不能超过2';
        }

        if (!$rna->save()) {
            var_dump($rna->errors);
            return 'RNA信息保存失败, ';
        }

        return 'success';
    }

    protected function findInfo($pt_id, $type = 0)//1 is dna, 2 is rna
    {
        $model = ($type == 1) ? models\SampleDna::findOne(['pt_id' => $pt_id]) : models\SampleRna::findOne(['pt_id' => $pt_id]);
        if ($model !== null) {
            ;
        } else {
            if ($type == 1) {
                $model = new models\SampleDna();
                $model->water_80 = 0;
                $model->water_4 = 0;
            } else {
                $model = new models\SampleRna();
                $model->rna_b = 0;
            }

            $model->pt_id = $pt_id;
            
        }

        $model->crt_name = Yii::$app->user->identity->username;
        $model->crt_time = date("Y-m-d H:i:s");
        
        return $model;
    }
}
